package io
{
	import flash.utils.ByteArray;
	
	public class PacketBuffer
	{
		private var buf:ByteArray = new ByteArray();
		
		public function PacketBuffer()
		{
		}
		
		public function push(byteArr:ByteArray):void
		{
			if(buf == null)
			{
				buf = byteArr;
			}else
			{
				buf.position = buf.length;
				buf.writeBytes(byteArr);
			}
		}
		
		public function getPackets():Array
		{
			var packets:Array = [];
			var ptr:uint = 0;
			buf.position = ptr;
			while(buf.bytesAvailable >= 4)
			{
				var len:uint = buf.readInt();
				if(buf.bytesAvailable < len)
				{
					var byteArr:ByteArray = new ByteArray;
					buf.position = ptr;
					byteArr.writeBytes(buf, 0, buf.bytesAvailable);            
					buf = byteArr;        
					return packets;
				}
				var bufIn:ByteArray = new ByteArray();
				buf.readBytes(bufIn, 0, len);
				bufIn.uncompress();
				packets.push(bufIn.readObject());
			}
			if(buf.bytesAvailable <= 0){
				clear();
			}
			return packets;
		}
		
		public function clear():void
		{
			buf=null;
		}
	}
}